import React, { Component, PropTypes } from 'react';
import { Form, Input, Icon, Button, Checkbox, Row, Col } from 'antd';
const FormItem = Form.Item;

let uuid = 0;
class DynamicFieldSet extends React.Component {
  constructor(props) {
    super(props);
    let { question } = this.props;
    this.state = {
      question: question,
      isChanged: false
    }
  }
  componentWillMount() {
    const { form, question } = this.props;

  }
  componentWillReceiveProps(nextProps) {
    // console.log(nextProps)

  }
  removeOneAnswer = (k) => {
    let { question } = this.state;
    let { questoins_options } = question;
    // We need at least one passenger
    console.log(k)
    if (questoins_options.length === 1) {
      return;
    } else {
      this.setState({
        question: Object.assign({}, question, { questoins_options: questoins_options.filter(q => (q.id !== k.id)) }),
        isChanged: true,
        isLoading: false
      })
    }
  }
  addOneAnswer = () => {
    console.log(this);
    let { question } = this.state;
    this.setState({
      question: Object.assign({}, question, { questoins_options: [...question.questoins_options, { id: (`id-${Date.parse(new Date())}`), name: `选项${question.questoins_options.length}`, isTrue: false }] }),
      isChanged: true
    })
  }
  handleSubmit = (e) => {
    e.preventDefault();
    let { question } = this.state;
    console.log(this.props.form.getFieldsValue());
    this.props.form.validateFields((err, values) => {
      if (!err) {
        // console.log('Received values of form: ', values, Object.keys(values));
        let answerArray = Object.keys(values);
        // console.log(answerArray,values[`${question._id}-name0`],`${question._id}-name0`,values,question)
        let newOptions = Array(answerArray.length / 3).fill().map((_, i) => {
          return { id: values[`${question._id}-id${i}`], name: values[`${question._id}-name${i}`], isTrue: values[`${question._id}-isTrue${i}`] || false }
        })
        console.log(answerArray, newOptions);
        let newQustion = Object.assign({}, question, { questoins_options: newOptions });
        this.setState({ isLoading: true });
        setTimeout(() => {
          this.props.updateOneQuestionById(newQustion);
          this.setState({ isLoading: false, isChanged: false, question: newQustion });

        }, 1000)
      }
    });
  }
  editAnwerInput = (e) => {
    this.setState({ isChanged: true })
  }
  toggleTrueAnswer = (checkedValues) => {
    this.setState({ isChanged: true })
    console.log('toggle', checkedValues, this)
  }
  render() {
    const { question } = this.state;

    const { getFieldDecorator, getFieldValue } = this.props.form;
    const originAnswerList = this.props.question.questoins_options;
    let answerList = question.questoins_options;
    // console.log(answerList);
    const formItemLayout = {
      labelCol: { span: 4 },
      wrapperCol: { span: 20 },
    };
    const formItemLayoutInline = {
      wrapperCol: { span: 20, offset: 0 },
    };
    const formItemLayoutWithOutLabel = {
      wrapperCol: { span: 20, offset: 4 },
    };
    // console.log(question.questoins_options);

    // console.log(keys,'获取选项列表');
    const formItems = answerList.map((k, index) => {
      // console.log(k);
      return (
        <Row gutter={10} key={index}>
          <Col span={4}>
        <FormItem
          {...formItemLayout }
          label={''}
          required={false}
          key={`isTrue-${k.id}`}
         
        >

        
          {getFieldDecorator(`${question._id}-isTrue${index}`, {
            initialValue:k.isTrue,
          })(

            <Checkbox defaultChecked={k.isTrue} onChange={this.toggleTrueAnswer} style={{float:'right'}}></Checkbox>
          )}
         
        </FormItem>
        <FormItem
          key={`id-${k.id}`}
          style={{display:"none"}}
          >
           {getFieldDecorator(`${question._id}-id${index}`, {
            initialValue:k.id
          })(

            <Input 
                />
          )}
        </FormItem>
          </Col>
          <Col span={12}>
            <FormItem
          {...formItemLayoutInline }
          label={''}
          required={false}
          key={`name-${k.id}`}
         
        >

          {getFieldDecorator(`${question._id}-name${index}`, {
            initialValue:k.name,
            rules: [{
              required: true,
              whitespace: true,
              message: "请输入一个选项",
            }],
          })(

            <Input placeholder="选项" 
                   style={{ width: '60%', marginRight: 8 }} 
                   onChange={this.editAnwerInput}
                />
          )}
          <Icon
            className="dynamic-delete-button"
            type="minus-circle-o"
            disabled={answerList.length === 1}
            onClick={() => this.removeOneAnswer(k)}
          />
        </FormItem>
          </Col>
        </Row>

      );
    });
    return (
      <Form onSubmit={this.handleSubmit}>
        {formItems}
        <FormItem {...formItemLayoutWithOutLabel}>
          <Button type="dashed" onClick={this.addOneAnswer} style={{ width: '60%' }}>
            <Icon type="plus" /> 添加一个选项
          </Button>
        </FormItem>
        <FormItem {...formItemLayoutWithOutLabel}>
          <Button type="primary" ref={question._id} loading={this.state.isLoading}  htmlType="submit" size="large" disabled={!this.state.isChanged}>保存修改</Button>
        </FormItem>
      </Form>
    );
  }
}

const WrappedDynamicFieldSet = Form.create()(DynamicFieldSet);

export default WrappedDynamicFieldSet
